package com.it.flowable.util;

import com.it.flowable.model.FourLevelModel;
import org.flowable.bpmn.model.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static com.it.flowable.util.ExtensionElementUtils.createExtensionAttribute;

public class ListenerUtils {

    public static FlowableListener createFlowableListener(String event, String implementation, String implementationType) {
        FlowableListener listener = new FlowableListener();
        listener.setEvent(event);
        listener.setImplementation(implementation);
        listener.setImplementationType(implementationType);

        // listener.getAttributes();
        // listener.getExtensionElements();
        // listener.getFieldExtensions();
        return listener;
    }

    public static ExtensionElement createExecutionListener(String event, String implementation, String implementationType) {

        ExtensionElement extensionElement = new ExtensionElement();
        extensionElement.setNamespace("http://flowable.org/bpmn");
        extensionElement.setNamespacePrefix("flowable");
        extensionElement.setName("executionListener");

        // addAttribute: ExtensionAttribute.name
        extensionElement.addAttribute(createExtensionAttribute("event", event));
        extensionElement.addAttribute(createExtensionAttribute(implementationType, implementation));
        // extensionElement.getAttributes().put()
        return extensionElement;
    }

    /**
     * 添加高级任务监听器
     */
    public static void addAdvancedTaskListener(UserTask task) {
        List<FlowableListener> listeners = Arrays.asList("create", "complete", "assignment").stream()
                .map(event -> createFlowableListener(event, FourLevelModel.ADVANCED_TASK_LISTENER, ImplementationType.IMPLEMENTATION_TYPE_CLASS))
                .collect(Collectors.toList());
        task.setTaskListeners(listeners);
    }

    /**
     * 添加Java委托
     */
    public static void addJavaDelegate(ServiceTask serviceTask, String delegateClass) {
        serviceTask.setImplementation(delegateClass);
        serviceTask.setImplementationType(ImplementationType.IMPLEMENTATION_TYPE_CLASS);
    }
}
